<?php
/**
 * Created by PhpStorm.
 * User: 王松
 * Time: 2018/4/13 17:17
 */

namespace App\Project\Traits;

trait PinYinSearchAble
{
    use SearchAble;

    protected $columnRelatePinYin = 'name';
    protected $columnsPinYin = ['intact_pinyin', 'pinyin'];

    public function pinYinSearch($input, $model, $map = [])
    {
        $wheres = $this->parseSearchQueryToWhere($input, $map);
        if ($wheres) {
            $other = $wheres;

            foreach ($wheres as $key => $where) {
                if (in_array('name', $where)) {

                    $model = $model->where(function ($query) use ($where) {
                        $query->where(...$where);
                        foreach ($this->columnsPinYin as $column) {
                            $query->orWhere($column, $where[1], $where[2]);
                        }
                    });

                    unset($other[$key]);
                }
            }

            $model = $model->where($other);
        }

        return $model;
    }
}